import { defaultRouterMap } from '@/router/routerConfig'
import { constantRouterMap } from '@/router/index'
import {hasPermission} from '@/utils/utils'
const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: [],
    permissionGotten : false,
    permissions : [],
    visitHomeCount : 0
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    },
    SET_PERMISSIONGOTTEN: (state, status) => {
      state.permissionGotten = status;
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
    },
    SET_VISITHOMECOUNT: (state, nowCount) => {
      state.visitHomeCount = nowCount;
    },
  },
  actions: {
    SET_VISITHOMECOUNT({commit}, nowCount) {
      return new Promise(resolve => {
        commit('SET_VISITHOMECOUNT', nowCount)
        resolve()
      });
    },
    PermissionGotten({commit}, status) {
      return new Promise(resolve => {
        commit('SET_PERMISSIONGOTTEN', status)
        resolve()
      });
    },
    GenerateRoutes({ commit }, userPermissionVo) {
      return new Promise(resolve => {

        let accessedRouters = [];
        if (userPermissionVo.superAdmin) {
          defaultRouterMap.forEach((rTmp) => {
            if (rTmp.path.indexOf("/inner") !== -1) {
              accessedRouters.push(rTmp);
            }
          });
        } else {
          let permissionList = userPermissionVo.permissionList;
          commit('SET_PERMISSIONS', permissionList)

          if (permissionList && permissionList.length && permissionList.length > 0) {
            let availableRouter = defaultRouterMap;
            for (let i = 0; i < availableRouter.length; i ++) {
              if (availableRouter[i].path.indexOf("/inner") !== -1) {
                continue;
              }
              if (hasPermission(permissionList, availableRouter[i])) {
                if (availableRouter[i].children && availableRouter[i].children.length && availableRouter[i].children.length > 0) {
                  let children = [];
                  for (let j = 0; j < availableRouter[i].children.length; j ++) {
                    if (hasPermission(permissionList, availableRouter[i].children[j])) {
                      children.push(availableRouter[i].children[j])
                    }
                  }
                  if (children.length > 0) {
                    availableRouter[i].children = children;
                    accessedRouters.push(availableRouter[i]);
                  }
                } else {
                  accessedRouters.push(availableRouter[i]);
                }
              }
            }
          } else {
            accessedRouters = []
          }
        }
        commit('SET_ROUTERS', accessedRouters)
        resolve()
      })
    }
  }
}

export default permission
